// Copyright 2024 Xiguan Inc
// Author: xiguan
// Email: xiguan.teng@qq.com
// Created on 2024/8/6
// This is ...
//

#include <absl/flags/flag.h>
#include <absl/flags/parse.h>
#include <absl/strings/str_format.h>
#include <grpcpp/ext/proto_server_reflection_plugin.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/health_check_service_interface.h>
#include <helloworld.grpc.pb.h>
#include <helloworld.pb.h>

#include <string>

ABSL_FLAG(uint16_t, listen_port, 23202, "Server listened port for the service");

class GreeterServiceImpl final : public helloworld::Greeter::Service {
  ::grpc::Status say_hello(::grpc::ServerContext            *context,
                           const ::helloworld::HelloRequest *request,
                           ::helloworld::HelloReply         *response) {
    auto prefix = "This is gRPC, Hello ";
    response->set_message(prefix + request->name());
    return ::grpc::Status::OK;
  }
};

void run_server(uint16_t port) {
  auto               server_address = absl::StrFormat("0.0.0.0:%d", port);
  GreeterServiceImpl service;

  grpc::EnableDefaultHealthCheckService(true);
  grpc::reflection::InitProtoReflectionServerBuilderPlugin();

  grpc::ServerBuilder builder;
  builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  builder.RegisterService(&service);
  std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
  std::cout << "Server listening on " << server_address << std::endl;
  server->Wait();
}

int main(int argc, char *argv[]) {
  absl::ParseCommandLine(argc, argv);
  run_server(absl::GetFlag(FLAGS_listen_port));
}